import { withDefaults } from 'vue';
<template>
  <div class="el-form">
    <slot></slot>
  </div>
</template>

<script lang="ts">
export default {
  name: 'ElForm'
}
</script>

<script setup lang="ts">
import { ref, PropType, provide } from 'vue'
import { Rules } from 'async-validator'
import { FormItem, key } from './types'
import { emitter } from '../../emitter'

const props = defineProps({
  model: { type: Object, required: true },
  rules: {
    type: Object as PropType<Rules>
  }
})

const items = ref<FormItem[]>([])
emitter.on('addFormItem', (item) => {
  items.value.push(item)
})

provide(key, {
  model: props.model,
  rules: props.rules
})

function validate(cb: (valid: boolean) => void) {
  return Promise.all(items.value.map((item) => item.validate()))
    .then(() => {
      cb(true)
    })
    .catch(() => {
      cb(false)
    })
}
defineExpose({ validate })
</script>

<style lang="scss" scoped>
@import '../../styles/mixin';

@include b(form) {
  box-sizing: border-box;
  flex-shrink: 0;
  width: 300px;
  margin-top: 20px;
}
</style>
